local tianxing = fk.CreateSkill {
  name = "lingling__tianxing",
  dynamic_desc = function (self, player, lang)
    return "lingling__tianxing_inner:"..
      player:getTableMark(self.name)[1]..":"..
      player:getTableMark(self.name)[2]..":"..
      player:getTableMark(self.name)[3]
  end,
}

Fk:loadTranslationTable{
  ["lingling__tianxing"] = "天幸",
  [":lingling__tianxing"] = "出牌阶段开始时，你可以将两张牌当【决斗】使用，若你因此对目标造成伤害，你摸一张牌，若你因此受到伤害，"..
  "你摸三张牌。回合结束时，随机互相调换此技能“一”、“两”、“三”的顺序。",

  [":lingling__tianxing_inner"] = "出牌阶段开始时，你可以将{1}张牌当【决斗】使用，若你因此对目标造成伤害，你摸{2}张牌，若你因此受到伤害，"..
  "你摸{3}张牌。回合结束时，随机互相调换此技能1、2、3的顺序。",

  ["#lingling__tianxing-use"] = "天幸：你可以将%arg张牌当当【决斗】使用",
}

tianxing:addEffect(fk.EventPhaseStart, {
  anim_type = "offensive",
  can_trigger = function (self, event, target, player, data)
    return target == player and player:hasSkill(tianxing.name) and player.phase == Player.Play and
      #player:getHandlyIds() + #player:getCardIds("e") >= player:getTableMark(tianxing.name)[1] and
      player:canUse(Fk:cloneCard("duel"))
  end,
  on_cost = function(self, event, target, player, data)
    local room = player.room
    local n = player:getTableMark(tianxing.name)[1]
    local use = room:askToUseVirtualCard(player, {
      name = "duel",
      skill_name = tianxing.name,
      prompt = "#lingling__tianxing-use:::"..n,
      cancelable = true,
      card_filter = {
        n = n,
      },
      skip = true,
    })
    if use then
      event:setCostData(self, {extra_data = use})
      return true
    end
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    local use = table.simpleClone(event:getCostData(self).extra_data)
    room:useCard(use)
    if use and use.damageDealt and not player.dead then
      if table.find(use.tos, function (p)
        return use.damageDealt[p]
      end) then
        player:drawCards(player:getTableMark(tianxing.name)[2], tianxing.name)
      end
      if not player.dead and use.damageDealt[player] then
        player:drawCards(player:getTableMark(tianxing.name)[3], tianxing.name)
      end
    end
  end,
})

tianxing:addEffect(fk.TurnEnd, {
  can_refresh = function(self, event, target, player, data)
    return target == player and player:hasSkill(tianxing.name, true)
  end,
  on_refresh = function (self, event, target, player, data)
    local mark = {1, 2, 3}
    table.shuffle(mark)
    player.room:setPlayerMark(player, tianxing.name, mark)
  end,
})

tianxing:addAcquireEffect(function (self, player, is_start)
  player.room:setPlayerMark(player, tianxing.name, {2, 1, 3})
end)

return tianxing
